﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ku.Common
{
    /// <summary>
    /// 时间辅助类
    /// </summary>
    public class TimeKit
    {
        public static int GetAge(object o, int defaultValue = 0)
        {
            try
            {
                DateTime dTime = Convert.ToDateTime(o);
                int now = int.Parse(DateTime.Today.ToString("yyyy"));
                int dob = int.Parse(dTime.ToString("yyyy"));
                int Age = (now - dob);
                return Age;
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>
        /// 转换成 日期字符串
        /// </summary>
        /// <param name="o"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string ConvertToDateTimeStr(object o, string format = "yyyy-MM-dd HH:mm")
        {
            string str = "";
            try
            {
                if (o != DBNull.Value && o != null && o.ToString() != String.Empty)
                {
                    return Convert.ToDateTime(o).ToString(format); ;
                }
                else
                {
                    return str;
                }
            }
            catch
            {
                return str;
            }
        }

        #region 将字符串转成  yyyy年MM月dd日
        public static string ConvertToChineseTimeStr(string inputValue)
        {
            string cnStr = "";
            if (!UtilHelper.IsNull(inputValue))
            {
                inputValue = inputValue.Replace("0:00:00", "").ToTrim();

                var reg_time_Str = @"^\d{4}[\-|\/|\.|年]\d{1,2}[\-|\/|\.|月]\d{1,2}(日?)$";//完整的日期格式

                var reg_time2_Str = @"^\d{4}[\-|\/|\.|年]\d{1,2}[\-|\/|\.|月]?$";//完整的 年月

                if (RegexHelper.IsMatch(inputValue, reg_time_Str))
                {
                    cnStr = inputValue.ToDateTimeStr("yyyy年M月d日");
                }
                else if (RegexHelper.IsMatch(inputValue, reg_time2_Str))
                {
                    cnStr = inputValue.ToDateTimeStr("yyyy年M月");
                }
                else
                {
                    cnStr = inputValue;
                }
            }
            return cnStr;
        }
        #endregion
    }
}
